package com.youbug.common.config;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

@Configuration
public class EncryptConfig {

    @Bean
    public AES aes(){

        // key：AES模式下，key必须为16位
        String key = "1234567812345678";
        // iv：偏移量，ECB模式不需要，CBC模式下必须为16位
        String iv = "1234567812345678";
        // AES aes = new AES(Mode.ECB, Padding.PKCS5Padding, key.getBytes());
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, key.getBytes(), iv.getBytes());

        return aes;
    }

    /**
     * 云服务器使用的加密解密秘钥
     * @return
     */
    @Bean
    public AES prodAes(){

        String absPath = System.getProperty("user.dir");
        System.out.println(absPath);
        String keyFilePath = absPath+"/prodAesKey.properties";
        Properties props = null;
        FileReader reader = null;
        try {
             reader = new FileReader(keyFilePath);

             props = new Properties();
             props.load(reader);

        } catch (IOException e) {
            return aes();
        }finally {
            if(reader != null){
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, props.getProperty("key").getBytes(),
                props.getProperty("iv").getBytes());

        return aes;
    }

//    public static void main(String[] args) {
//
//        // key：AES模式下，key必须为16位
//        String key = "1234567812345678";
//        // iv：偏移量，ECB模式不需要，CBC模式下必须为16位
//        String iv = "1234567812345678";
//        // AES aes = new AES(Mode.ECB, Padding.PKCS5Padding, key.getBytes());
//        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, key.getBytes(), iv.getBytes());
//
//        System.out.println(aes.encryptBase64("123456".getBytes()));
//    }
}
